# 创建会员管理主页面
<template>
  <div class="member-management">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>会员总数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.totalMembers }}</div>
            <div class="trend">
              较上月
              <span :class="statistics.memberTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.memberTrend) }}%
                <el-icon>
                  <component :is="statistics.memberTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>本月新增</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.newMembers }}</div>
            <div class="percentage">
              占比 {{ statistics.newMemberPercentage }}%
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>活跃会员</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.activeMembers }}</div>
            <div class="percentage">
              占比 {{ statistics.activeMemberPercentage }}%
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>会员消费</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥{{ statistics.totalConsumption }}</div>
            <div class="trend">
              较上月
              <span :class="statistics.consumptionTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.consumptionTrend) }}%
                <el-icon>
                  <component :is="statistics.consumptionTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 会员等级管理 -->
    <el-card class="level-card">
      <template #header>
        <div class="card-header">
          <span>会员等级</span>
          <el-button type="primary" @click="handleAddLevel">添加等级</el-button>
        </div>
      </template>
      <el-table :data="levelList" border style="width: 100%">
        <el-table-column prop="name" label="等级名称" width="150" />
        <el-table-column prop="code" label="等级编码" width="120" />
        <el-table-column prop="icon" label="等级图标" width="100">
          <template #default="{ row }">
            <el-image 
              :src="row.icon" 
              :preview-src-list="[row.icon]"
              fit="contain"
              class="level-icon"
            />
          </template>
        </el-table-column>
        <el-table-column prop="upgradeCondition" label="升级条件" width="200">
          <template #default="{ row }">
            <div>消费满 {{ row.upgradeAmount }} 元</div>
            <div>或累计积分 {{ row.upgradePoints }} 分</div>
          </template>
        </el-table-column>
        <el-table-column prop="discount" label="折扣" width="100">
          <template #default="{ row }">
            {{ row.discount }} 折
          </template>
        </el-table-column>
        <el-table-column prop="pointsRate" label="积分倍率" width="100">
          <template #default="{ row }">
            {{ row.pointsRate }} 倍
          </template>
        </el-table-column>
        <el-table-column prop="memberCount" label="会员数量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'enabled' ? 'success' : 'info'">
              {{ row.status === 'enabled' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEditLevel(row)">
              编辑
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDeleteLevel(row)"
              :disabled="row.memberCount > 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 会员标签管理 -->
    <el-card class="tag-card">
      <template #header>
        <div class="card-header">
          <span>会员标签</span>
          <el-button type="primary" @click="handleAddTag">添加标签</el-button>
        </div>
      </template>
      <div class="tag-list">
        <el-tag
          v-for="tag in tagList"
          :key="tag.id"
          :type="tag.type"
          class="tag-item"
          closable
          @close="handleDeleteTag(tag)"
        >
          {{ tag.name }}
          <span class="tag-count">({{ tag.memberCount }})</span>
        </el-tag>
      </div>
    </el-card>

    <!-- 会员列表 -->
    <el-card class="member-card">
      <template #header>
        <div class="card-header">
          <div class="search-form">
            <el-form :model="searchForm" inline>
              <el-form-item label="会员等级">
                <el-select v-model="searchForm.levelId" placeholder="请选择" clearable>
                  <el-option
                    v-for="level in levelOptions"
                    :key="level.id"
                    :label="level.name"
                    :value="level.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="会员标签">
                <el-select v-model="searchForm.tagIds" multiple placeholder="请选择" clearable>
                  <el-option
                    v-for="tag in tagOptions"
                    :key="tag.id"
                    :label="tag.name"
                    :value="tag.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="注册时间">
                <el-date-picker
                  v-model="searchForm.registerTime"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item label="关键词">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="会员昵称/手机号"
                  clearable
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="action-buttons">
            <el-button type="success" @click="handleExport">导出会员</el-button>
            <el-button type="warning" @click="handleBatchTag">批量打标签</el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="memberList"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="会员信息" min-width="200">
          <template #default="{ row }">
            <div class="member-info">
              <el-avatar :src="row.avatar" :size="40" />
              <div class="member-detail">
                <div class="member-name">{{ row.nickname }}</div>
                <div class="member-phone">{{ row.phone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="levelName" label="会员等级" width="120">
          <template #default="{ row }">
            <el-tag :type="row.levelType">{{ row.levelName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="会员标签" min-width="200">
          <template #default="{ row }">
            <el-tag
              v-for="tag in row.tags"
              :key="tag.id"
              :type="tag.type"
              class="member-tag"
            >
              {{ tag.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分" width="100" />
        <el-table-column prop="totalConsumption" label="消费金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalConsumption.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastConsumptionTime" label="最后消费" width="180" />
        <el-table-column prop="registerTime" label="注册时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button type="success" link @click="handleEditMember(row)">
              编辑
            </el-button>
            <el-button type="warning" link @click="handleAdjustPoints(row)">
              积分
            </el-button>
            <el-button type="info" link @click="handleViewRecords(row)">
              记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 等级表单对话框 -->
    <el-dialog
      v-model="levelDialogVisible"
      :title="levelForm.id ? '编辑等级' : '添加等级'"
      width="500px"
    >
      <el-form
        ref="levelFormRef"
        :model="levelForm"
        :rules="levelFormRules"
        label-width="100px"
      >
        <el-form-item label="等级名称" prop="name">
          <el-input v-model="levelForm.name" placeholder="请输入等级名称" />
        </el-form-item>
        <el-form-item label="等级编码" prop="code">
          <el-input v-model="levelForm.code" placeholder="请输入等级编码" />
        </el-form-item>
        <el-form-item label="等级图标" prop="icon">
          <el-upload
            class="level-icon-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleIconSuccess"
            :before-upload="beforeIconUpload"
          >
            <img v-if="levelForm.icon" :src="levelForm.icon" class="level-icon" />
            <el-icon v-else class="level-icon-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="升级条件">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="消费金额" prop="upgradeAmount">
                <el-input-number
                  v-model="levelForm.upgradeAmount"
                  :min="0"
                  :precision="2"
                  :step="100"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="累计积分" prop="upgradePoints">
                <el-input-number
                  v-model="levelForm.upgradePoints"
                  :min="0"
                  :precision="0"
                  :step="100"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="折扣" prop="discount">
          <el-input-number
            v-model="levelForm.discount"
            :min="0"
            :max="10"
            :precision="1"
            :step="0.1"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="积分倍率" prop="pointsRate">
          <el-input-number
            v-model="levelForm.pointsRate"
            :min="1"
            :max="10"
            :precision="1"
            :step="0.1"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="levelForm.status">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="levelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleLevelSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 标签表单对话框 -->
    <el-dialog
      v-model="tagDialogVisible"
      :title="tagForm.id ? '编辑标签' : '添加标签'"
      width="400px"
    >
      <el-form
        ref="tagFormRef"
        :model="tagForm"
        :rules="tagFormRules"
        label-width="100px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="tagForm.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="标签类型" prop="type">
          <el-select v-model="tagForm.type" placeholder="请选择标签类型">
            <el-option label="默认" value="" />
            <el-option label="成功" value="success" />
            <el-option label="警告" value="warning" />
            <el-option label="危险" value="danger" />
            <el-option label="信息" value="info" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleTagSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 积分调整对话框 -->
    <el-dialog
      v-model="pointsDialogVisible"
      title="调整积分"
      width="500px"
    >
      <el-form
        ref="pointsFormRef"
        :model="pointsForm"
        :rules="pointsFormRules"
        label-width="100px"
      >
        <el-form-item label="会员昵称">
          <span>{{ currentMember?.nickname }}</span>
        </el-form-item>
        <el-form-item label="当前积分">
          <span>{{ currentMember?.points }}</span>
        </el-form-item>
        <el-form-item label="调整方式" prop="type">
          <el-radio-group v-model="pointsForm.type">
            <el-radio label="increase">增加</el-radio>
            <el-radio label="decrease">减少</el-radio>
            <el-radio label="set">直接设置</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="调整数量" prop="points">
          <el-input-number
            v-model="pointsForm.points"
            :min="0"
            :precision="0"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="调整原因" prop="reason">
          <el-input
            v-model="pointsForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入调整原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="pointsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePointsSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量打标签对话框 -->
    <el-dialog
      v-model="batchTagDialogVisible"
      title="批量打标签"
      width="500px"
    >
      <el-form
        ref="batchTagFormRef"
        :model="batchTagForm"
        :rules="batchTagFormRules"
        label-width="100px"
      >
        <el-form-item label="选择标签" prop="tagIds">
          <el-select
            v-model="batchTagForm.tagIds"
            multiple
            placeholder="请选择标签"
          >
            <el-option
              v-for="tag in tagOptions"
              :key="tag.id"
              :label="tag.name"
              :value="tag.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="操作类型" prop="operation">
          <el-radio-group v-model="batchTagForm.operation">
            <el-radio label="add">添加标签</el-radio>
            <el-radio label="remove">移除标签</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchTagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchTagSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowUp, ArrowDown, Plus } from '@element-plus/icons-vue'
import {
  getMerchantMemberStatistics,
  getMerchantMemberLevelList,
  createMerchantMemberLevel,
  updateMerchantMemberLevel,
  deleteMerchantMemberLevel,
  getMerchantMemberTagList,
  createMerchantMemberTag,
  updateMerchantMemberTag,
  deleteMerchantMemberTag,
  getMerchantMemberList,
  updateMerchantMemberPoints,
  batchUpdateMerchantMemberTags,
  exportMerchantMembers
} from '@/api/merchant'

// 统计数据
const statistics = reactive({
  totalMembers: 0,
  memberTrend: 0,
  newMembers: 0,
  newMemberPercentage: 0,
  activeMembers: 0,
  activeMemberPercentage: 0,
  totalConsumption: 0,
  consumptionTrend: 0
})

// 等级列表
const levelList = ref([])
const levelOptions = ref([])

// 标签列表
const tagList = ref([])
const tagOptions = ref([])

// 会员列表
const loading = ref(false)
const memberList = ref([])
const selectedMembers = ref([])

// 搜索表单
const searchForm = reactive({
  levelId: '',
  tagIds: [],
  registerTime: [],
  keyword: ''
})

// 分页
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 等级表单
const levelDialogVisible = ref(false)
const levelFormRef = ref(null)
const levelForm = reactive({
  id: '',
  name: '',
  code: '',
  icon: '',
  upgradeAmount: 0,
  upgradePoints: 0,
  discount: 10,
  pointsRate: 1,
  status: 'enabled'
})

// 标签表单
const tagDialogVisible = ref(false)
const tagFormRef = ref(null)
const tagForm = reactive({
  id: '',
  name: '',
  type: ''
})

// 积分表单
const pointsDialogVisible = ref(false)
const pointsFormRef = ref(null)
const pointsForm = reactive({
  type: 'increase',
  points: 0,
  reason: ''
})
const currentMember = ref(null)

// 批量打标签表单
const batchTagDialogVisible = ref(false)
const batchTagFormRef = ref(null)
const batchTagForm = reactive({
  tagIds: [],
  operation: 'add'
})

// 上传相关
const uploadUrl = import.meta.env.VITE_API_URL + '/merchant/upload'

// 表单验证规则
const levelFormRules = {
  name: [{ required: true, message: '请输入等级名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入等级编码', trigger: 'blur' }],
  icon: [{ required: true, message: '请上传等级图标', trigger: 'change' }],
  upgradeAmount: [{ required: true, message: '请输入升级消费金额', trigger: 'blur' }],
  upgradePoints: [{ required: true, message: '请输入升级所需积分', trigger: 'blur' }],
  discount: [{ required: true, message: '请输入折扣', trigger: 'blur' }],
  pointsRate: [{ required: true, message: '请输入积分倍率', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const tagFormRules = {
  name: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择标签类型', trigger: 'change' }]
}

const pointsFormRules = {
  type: [{ required: true, message: '请选择调整方式', trigger: 'change' }],
  points: [{ required: true, message: '请输入调整数量', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入调整原因', trigger: 'blur' }]
}

const batchTagFormRules = {
  tagIds: [{ required: true, message: '请选择标签', trigger: 'change' }],
  operation: [{ required: true, message: '请选择操作类型', trigger: 'change' }]
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const { data } = await getMerchantMemberStatistics()
    Object.assign(statistics, data)
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取等级列表
const getLevelList = async () => {
  try {
    const { data } = await getMerchantMemberLevelList()
    levelList.value = data
    levelOptions.value = data.map(level => ({
      id: level.id,
      name: level.name
    }))
  } catch (error) {
    console.error('获取等级列表失败:', error)
    ElMessage.error('获取等级列表失败')
  }
}

// 获取标签列表
const getTagList = async () => {
  try {
    const { data } = await getMerchantMemberTagList()
    tagList.value = data
    tagOptions.value = data.map(tag => ({
      id: tag.id,
      name: tag.name
    }))
  } catch (error) {
    console.error('获取标签列表失败:', error)
    ElMessage.error('获取标签列表失败')
  }
}

// 获取会员列表
const getMemberList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: page.current,
      size: page.size
    }
    const { data } = await getMerchantMemberList(params)
    memberList.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取会员列表失败:', error)
    ElMessage.error('获取会员列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getMemberList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'tagIds' ? [] : key === 'registerTime' ? [] : ''
  })
  handleSearch()
}

// 选择行变化
const handleSelectionChange = (rows) => {
  selectedMembers.value = rows
}

// 添加等级
const handleAddLevel = () => {
  Object.keys(levelForm).forEach(key => {
    levelForm[key] = key === 'status' ? 'enabled' : 
                    key === 'discount' ? 10 :
                    key === 'pointsRate' ? 1 : 0
  })
  levelForm.id = ''
  levelDialogVisible.value = true
}

// 编辑等级
const handleEditLevel = (row) => {
  Object.assign(levelForm, row)
  levelDialogVisible.value = true
}

// 删除等级
const handleDeleteLevel = async (row) => {
  if (row.memberCount > 0) {
    ElMessage.warning('该等级下存在会员，无法删除')
    return
  }
  try {
    await ElMessageBox.confirm('确认删除该等级吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantMemberLevel(row.id)
    ElMessage.success('删除成功')
    getLevelList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除等级失败:', error)
    }
  }
}

// 提交等级表单
const handleLevelSubmit = async () => {
  if (!levelFormRef.value) return
  
  try {
    await levelFormRef.value.validate()
    if (levelForm.id) {
      await updateMerchantMemberLevel(levelForm.id, levelForm)
      ElMessage.success('更新成功')
    } else {
      await createMerchantMemberLevel(levelForm)
      ElMessage.success('创建成功')
    }
    levelDialogVisible.value = false
    getLevelList()
  } catch (error) {
    console.error('提交等级失败:', error)
  }
}

// 添加标签
const handleAddTag = () => {
  Object.keys(tagForm).forEach(key => {
    tagForm[key] = ''
  })
  tagForm.id = ''
  tagDialogVisible.value = true
}

// 删除标签
const handleDeleteTag = async (tag) => {
  if (tag.memberCount > 0) {
    ElMessage.warning('该标签下存在会员，无法删除')
    return
  }
  try {
    await ElMessageBox.confirm('确认删除该标签吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantMemberTag(tag.id)
    ElMessage.success('删除成功')
    getTagList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除标签失败:', error)
    }
  }
}

// 提交标签表单
const handleTagSubmit = async () => {
  if (!tagFormRef.value) return
  
  try {
    await tagFormRef.value.validate()
    if (tagForm.id) {
      await updateMerchantMemberTag(tagForm.id, tagForm)
      ElMessage.success('更新成功')
    } else {
      await createMerchantMemberTag(tagForm)
      ElMessage.success('创建成功')
    }
    tagDialogVisible.value = false
    getTagList()
  } catch (error) {
    console.error('提交标签失败:', error)
  }
}

// 调整积分
const handleAdjustPoints = (row) => {
  currentMember.value = row
  Object.keys(pointsForm).forEach(key => {
    pointsForm[key] = key === 'type' ? 'increase' : ''
  })
  pointsForm.points = 0
  pointsDialogVisible.value = true
}

// 提交积分调整
const handlePointsSubmit = async () => {
  if (!pointsFormRef.value) return
  
  try {
    await pointsFormRef.value.validate()
    const { type, points, reason } = pointsForm
    let finalPoints = points
    
    if (type === 'decrease') {
      finalPoints = -points
    } else if (type === 'set') {
      finalPoints = points - currentMember.value.points
    }
    
    await updateMerchantMemberPoints(currentMember.value.id, {
      points: finalPoints,
      reason
    })
    ElMessage.success('积分调整成功')
    pointsDialogVisible.value = false
    getMemberList()
  } catch (error) {
    console.error('调整积分失败:', error)
  }
}

// 批量打标签
const handleBatchTag = () => {
  if (selectedMembers.value.length === 0) {
    ElMessage.warning('请选择要打标签的会员')
    return
  }
  batchTagForm.tagIds = []
  batchTagForm.operation = 'add'
  batchTagDialogVisible.value = true
}

// 提交批量打标签
const handleBatchTagSubmit = async () => {
  if (!batchTagFormRef.value) return
  
  try {
    await batchTagFormRef.value.validate()
    const memberIds = selectedMembers.value.map(member => member.id)
    await batchUpdateMerchantMemberTags({
      memberIds,
      tagIds: batchTagForm.tagIds,
      operation: batchTagForm.operation
    })
    ElMessage.success('批量打标签成功')
    batchTagDialogVisible.value = false
    getMemberList()
  } catch (error) {
    console.error('批量打标签失败:', error)
  }
}

// 导出会员
const handleExport = async () => {
  try {
    const params = { ...searchForm }
    await exportMerchantMembers(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 上传图标
const handleIconSuccess = (response) => {
  levelForm.icon = response.data.url
  ElMessage.success('上传成功')
}

const beforeIconUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB')
    return false
  }
  return true
}

// 分页
const handleSizeChange = (val) => {
  page.size = val
  getMemberList()
}

const handleCurrentChange = (val) => {
  page.current = val
  getMemberList()
}

onMounted(() => {
  getStatistics()
  getLevelList()
  getTagList()
  getMemberList()
})
</script>

<style lang="scss" scoped>
.member-management {
  padding: 20px;

  .statistics-cards {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-content {
      text-align: center;

      .amount {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 10px;
      }

      .trend {
        font-size: 14px;
        color: var(--el-text-color-secondary);

        .up {
          color: var(--el-color-success);
        }

        .down {
          color: var(--el-color-danger);
        }
      }

      .percentage {
        font-size: 14px;
        color: var(--el-text-color-secondary);
      }
    }
  }

  .level-card,
  .tag-card,
  .member-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .search-form {
        flex: 1;
        margin-right: 20px;
      }

      .action-buttons {
        display: flex;
        gap: 10px;
      }
    }
  }

  .level-icon-uploader {
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .level-icon-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      text-align: center;
      line-height: 100px;
    }

    .level-icon {
      width: 100px;
      height: 100px;
      display: block;
    }
  }

  .tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .tag-item {
      .tag-count {
        margin-left: 5px;
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }
  }

  .member-info {
    display: flex;
    align-items: center;
    gap: 10px;

    .member-detail {
      .member-name {
        font-weight: bold;
        margin-bottom: 5px;
      }

      .member-phone {
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }
  }

  .member-tag {
    margin-right: 5px;
    margin-bottom: 5px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 